﻿using System;
using System.Collections.Generic;

namespace Allegro.Mathlib
{
    public static partial class Statistics
    {
        /// <summary>
        /// Fisher-Yates shuffle of an array
        /// Cf. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
        /// </summary>
        /// <param name="array"></param>
        public static void Shuffle<T>(T[] array)
        {
            Random random = new Random();   // i.e., java.util.Random.
            int n = array.Length;        // The number of items left to shuffle (loop invariant).
            while (n > 1)
            {
                int k = random.Next(n);  // 0 <= k < n.
                n--;                     // n is now the last pertinent index;
                T temp = array[n];     // swap array[n] with array[k] (does nothing if k == n).
                array[n] = array[k];
                array[k] = temp;
            }
        }
    }
}
